import axios from 'axios'
import { URL, RESPONSE_DIR } from '../config'

/**
 * 封装Get请求
 * @param url {string} 请求地址
 * @param params {object} 请求参数
 * @returns {Promise.<TResult>}
 * @constructor
 */
export function Get (url, params) {
  return axios.get(URL.SERVER_URL + url, {
    params: params || {}
  }).then(function (response) {
    // console.log(response.data)
    // let JsonResponse = JSON.parse(response).data
    let JsonResponse = response.data
    if (JsonResponse.code === 20000) {
      return JsonResponse.data
    } else if (JsonResponse.code === 40001) {
      alert(RESPONSE_DIR[40001])
      // 跳转登录
    } else {
      alert(JsonResponse.message)
      throw new Error(JsonResponse.message)
    }
  }).catch(function (error) {
    console.log(error)
  })
}

/**
 * 封装Post请求
 * @param url {string} 请求地址
 * @param params {object} 请求参数
 * @returns {Promise.<TResult>}
 * @constructor
 */
export function Post (url, params) {
  let data = new URLSearchParams()
  if (params) {
    Object.keys(params).forEach(key => {
      data.append(key, params[key])
    })
  }
  return axios.post(URL.SERVER_URL + url, data).then(function (response) {
    // console.log(response.data)
    // let JsonResponse = JSON.parse(response).data
    let JsonResponse = response.data
    if (JsonResponse.code === 20000) {
      return JsonResponse.data
    } else if (JsonResponse.code === 40001) {
      alert(RESPONSE_DIR[40001])
      // 跳转登录
    } else {
      alert(JsonResponse.message)
      throw new Error('错误编号: ' + JsonResponse.code)
    }
  }).catch(function (error) {
    console.log(error)
  })
}

export function getItem (key) {
  let item = localStorage.getItem(key)
  return item ? JSON.parse(item) : null
}

export function setItem (key, item) {
  localStorage.setItem(key, JSON.stringify(item))
}

export function getSessionItem (key) {
  let item = sessionStorage.getItem(key)
  return item ? JSON.parse(item) : null
}

export function setSessionItem (key, item) {
  sessionStorage.setItem(key, JSON.stringify(item))
}

export const loadState = key => {
  try {
    const serializedState = localStorage.getItem(key)
    if (serializedState === null) {
      return undefined
    }
    return JSON.parse(serializedState)
  } catch (err) {
    return undefined
  }
}

export const saveState = (key, state) => {
  try {
    const serializedState = JSON.stringify(state)
    localStorage.setItem(key, serializedState)
  } catch (err) {
    // ignore errors.
  }
}

export function throttle (fn, interval) {
  let self = fn
  let _this = this
  let timer
  let firstTime = true
  return function () {
    let args = arguments
    if (firstTime) {
      self.apply(_this, args)
      firstTime = false
      return false
    }
    if (timer) {
      return false
    }

    timer = setTimeout(function () {
      clearTimeout(timer)
      timer = null
      self.apply(_this, args)
    }, interval || 500)
  }
}
